<?php
header( 'Content-Type: text/html;charset=utf-8' );

$objeto = json_decode($_POST['datos']);

$name = $objeto->name;
$surname = $objeto->surname; 
$mail = $objeto->mail;
$user = $objeto->user;
$password = $objeto->password;
$password2 = $objeto->password2;
$state = false;
$contarErrores = 0;
$errorName = " ";
$errorSurname = " ";
$errorMail = " ";
$errorPass = " ";


if ($name == "" || strlen($name) < 3) {
	$errorName = "El nombre no es correcto";
	$contarErrores++;

}
if ($surname == "" || strlen($surname) < 3) {
	$errorSurname = "El apellido no es correcto";
	$contarErrores++;

}

if ($mail == "") {
	$errorMail = "Falta introducir el mail";
	$contarErrores++;

} else if (!$correcto = isMail($mail)) {
	$errorMail = "El mail no es v�lido";
	$contarErrores++;
}

if ($password == "" || $password2 == "") {
	$errorPass = "No ha introducido contrase�a";
	$contarErrores++;
} else if (!$password == $password2) {
	$errorPass = "Las contrase�as deben coincidir";
	$contarErrores++;
} else if (!$correcto = isPass($password)) {
	$errorPass = "La contrase�a es poco segura";
	$contarErrores++;
}

if ($user == "" ||strlen($user) < 3 || strlen($user) > 10){
	$errorUser = "nombre de usuario incorrecto";
	$contarErrores++;
	$userName = false;
}else{
	$conexion = mysql_connect("localhost", "root", "root") or die("No se pudo conectar</br>");
	mysql_query("SET NAMES 'utf8'");
	
	mysql_select_db("LeisureTime") or die("Verifique la Base de Datos</br>");
	$query = "SELECT user FROM Usuarios WHERE user='$user'";
	$result = mysql_query($query);
	
	
	if(!$result){
		header("Location: ../php/error.php");
	}else if(mysql_num_rows($result) == 0){
		$userName = true;
		$state = true;
		$errorUser = " ";
	}else{
		$userName = false;
		$errorUser = "El nombre de ususario seleccionado ya existe";
	}
	
}

if(!$userName || $contarErrores != 0){
	/*header("Location: ../html/registro.html");*/
	$errores = array($state,$errorName,$errorSurname,$errorMail,$errorPass,$errorUser);
	echo json_encode($errores);
	
}else{
	$insertar = "INSERT INTO Usuarios(nombre,apellido,user,password,email) VALUES ('$name','$surname','$user','$password','$mail')";
	
	if (!mysql_query($insertar)) {
		header("Location: ../php/error.php");
	}else{
		$estado = array($state);
		echo json_encode($estado);
	}
	
	}

/*mysql_close();*/

function isMail($mail) {
	$verdad = preg_match('/^(\w)([.]*[_]*[-]*\w)+@([a-z])+([.]*[a-z])*[.]([a-z]{2,3})$/', $mail);
	return $verdad;
}

function isPass($pass) {
	$verdad = preg_match('/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$/', $pass);
	return $verdad;
}
?>